package com.alex.cms.web.controllers;


import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alex.cms.domain.CmsCategory;
import com.alex.cms.domain.CmsChannel;
import com.alex.cms.domain.CmsUser;
import com.alex.cms.service.ICmsCategoryService;
import com.alex.cms.service.ICmsChannelService;
import com.alex.cms.web.constants.CMSConstants;
import com.alex.cms.web.vo.CategoryVo;
import com.alex.cms.web.vo.ResultVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bawei.common.Exception.CMSSystemException;
import com.bawei.common.utils.AssertionUtil;

/**
 * <p>
 * 分类表 前端控制器
 * </p>
 *
 * @author alex
 * @since 2019-09-11
 */
@Controller
@RequestMapping("/category")
public class CmsCategoryController {
	
	@Autowired
	private ICmsChannelService channelService;
	
	@Autowired
	private ICmsCategoryService categoryService;
	
	@RequestMapping("/toAddCategory")
	public ModelAndView showCategory() {
		// 指定跳转的jsp页面
		ModelAndView mav = new ModelAndView("/admin/category-edit");
		// 页面需要的分类信息
		CategoryVo categoryVo = new CategoryVo();
		List<CmsChannel> list =channelService.list();
		mav.addObject("category", categoryVo);
		mav.addObject("channels",list);
		return mav;
	}

	@RequestMapping(value = "/edit", method = RequestMethod.POST)
	public ModelAndView editchannel(CategoryVo categoryVo,HttpSession session) {
		ModelAndView mav = new ModelAndView("redirect:/admin/categories");
		// 获取登录时保存到session的用户信息
		CmsUser user = (CmsUser) session.getAttribute(CMSConstants.LOGIN_USER);
		String message = "";
		if (user == null) {
			message = CMSConstants.USER_DO_NOT_LOGIN;
			mav.setViewName("redirect:/user/login");
			mav.addObject("message", message);
			return mav;
		}
		if(categoryVo.getId() == null){
			CmsCategory category = new CmsCategory();
			category.setId(categoryVo.getId());
			category.setChannelId(categoryVo.getChannelId());
			category.setName(categoryVo.getName());
			List<CmsCategory> list = categoryService.list(new QueryWrapper<CmsCategory>().eq("channel_id", categoryVo.getChannelId()).orderByDesc("sorted"));
			if(CollectionUtils.isEmpty(list)){
				category.setSorted(1);
			}else{
				category.setSorted(list.get(0).getSorted()+1);
			}
			categoryService.save(category);
		}else{
			CmsCategory category = categoryService.getById(categoryVo.getId());
			category.setName(categoryVo.getName());
			category.setChannelId(categoryVo.getChannelId());
			categoryService.updateById(category);
		}
		return mav;
	}

	@RequestMapping("/upMove")
	public ModelAndView moveUp(@RequestParam("categoryId") Integer categoryId) {
		ModelAndView mav = new ModelAndView("redirect:/admin/categories");
		CmsCategory category = categoryService.getById(categoryId);
		QueryWrapper<CmsCategory> queryWrapper = new QueryWrapper<CmsCategory>();
		queryWrapper = queryWrapper.eq("channel_id", category.getChannelId()).orderByAsc("sorted");
		List<CmsCategory> categories = categoryService.list(queryWrapper);
		List<CmsCategory> cList = new ArrayList<CmsCategory>();
		for (int i = 0; i < categories.size(); i++) {
			if (categories.get(0).getId() == categoryId) {
				break;
			}
			if (i == 0) {
				categories.get(0).setSorted(categories.get(categories.size() - 1).getSorted());
				cList.add(categories.get(0));
				continue;
			}
			categories.get(i).setSorted(categories.get(i).getSorted() - 1);
			cList.add(categories.get(i));
		}
		categoryService.updateBatchById(cList);
		return mav;
	}

	@RequestMapping("/downMove")
	public ModelAndView moveDown(@RequestParam("categoryId") Integer categoryId) {
		ModelAndView mav = new ModelAndView("redirect:/admin/categories");
		CmsCategory category = categoryService.getById(categoryId);
		QueryWrapper<CmsCategory> queryWrapper = new QueryWrapper<CmsCategory>();
		queryWrapper = queryWrapper.eq("channel_id", category.getChannelId()).orderByAsc("sorted");
		List<CmsCategory> categories = categoryService.list(queryWrapper);
		List<CmsCategory> cList = new ArrayList<CmsCategory>();
		for (int i = 0; i < categories.size(); i++) {
			if (categories.get(categories.size() - 1).getId() == categoryId) {
				break;
			}
			if (i == categories.size() - 1) {
				categories.get(categories.size() - 1).setSorted(categories.get(0).getSorted()-1);
				cList.add(categories.get(categories.size() - 1));
				continue;
			}
			categories.get(i).setSorted(categories.get(i).getSorted() + 1);
			cList.add(categories.get(i));
		}
		categoryService.updateBatchById(cList);
		return mav;
	}

	@RequestMapping("/toEditCategory")
	public ModelAndView showChannelPage(@RequestParam("categoryId") Integer categoryId) {
				ModelAndView mav = new ModelAndView("admin/category-edit");
				QueryWrapper<CategoryVo> queryWrapper = new QueryWrapper<CategoryVo>();
				queryWrapper = queryWrapper.eq("category.id", categoryId);
				List<CategoryVo> categories = categoryService.getAllCategoriesAsc(queryWrapper);
				CategoryVo categoryVo = categories.get(0);
				try {

					// 断言要抛出异常，断言之后执行的语句都是正确流程
					AssertionUtil.assertFalse(categoryVo == null, CMSConstants.CHANNEL_IS_NOT_EXIST);

					List<CmsChannel> list =channelService.list();
					mav.addObject("channels", list);
					mav.addObject("category", categoryVo);
				} catch (CMSSystemException e) {
					// 视图仍然定位到文章编辑页面，错误消息在编辑页面显示
					mav.addObject("message", e.getMessage());
				}

				return mav;
	}

	@RequestMapping("/removeCategory")
	@ResponseBody
	public ResultVo removeCategoryById(@RequestParam("id") Integer categoryId) {
		// ajax定义的返回数据结构，所以定义这个对象的时候看ajax的data结构是什么
		ResultVo result = new ResultVo();
		// 根据配置ID删除，返回结果
		boolean removeResult = categoryService.removeById(categoryId);
		// 返回结果都统一放在constants中，便于维护
		result.setStatus(removeResult ? CMSConstants.RESULT_STATUS_SUCCESS : CMSConstants.RESULT_STATUS_ERROR);
		result.setMessage(removeResult ? CMSConstants.RESULT_DELETE_MESSAGE_SUCCESS : CMSConstants.RESULT_DELETE_MESSAGE_ERROR);

		return result;
	}
}
